package cn.icanci.loopstack.amc.cloud.biz.service.impl;

import cn.hutool.json.JSONUtil;
import cn.icanci.loopstack.amc.cloud.biz.repository.AmcMockCallHolder;
import cn.icanci.loopstack.amc.cloud.biz.repository.AmcMockCallRepository;
import cn.icanci.loopstack.amc.cloud.biz.service.MockCallService;
import cn.icanci.loopstack.amc.cloud.common.model.MockCallWrapper;

import javax.annotation.Resource;
import javax.script.SimpleBindings;

import org.springframework.stereotype.Service;

/**
 * @author icanci
 * @since 1.0 Created in 2023/01/16 15:53
 */
@Service
public class MockCallServiceImpl implements MockCallService {
    @Resource
    private AmcMockCallRepository amcMockCallRepository;

    @Override
    public MockCallWrapper mockCall(String mockCallUuid, String mockRequest) {
        AmcMockCallHolder holder = amcMockCallRepository.getAmcMockCallHolder(mockCallUuid);
        if (holder == null) {
            return MockCallWrapper.fail(mockCallUuid, "Cannot found the Mock Config for:" + mockCallUuid);
        }

        try {
            SimpleBindings simpleBindings = JSONUtil.toBean(mockRequest, SimpleBindings.class);

            Object ret = null;
            // 优先处理实例
            if (holder.getInstance() != null) {
                ret = holder.getInstance().execute(mockRequest);
            } else if (holder.getCompiledScript() != null) {
                ret = holder.getCompiledScript().eval(simpleBindings);
            } else {
                ret = holder.getScriptEngine().eval(holder.getScriptContent(), simpleBindings);
            }
            return buildWrapper(ret, holder, mockRequest);
        } catch (Exception e) {
            return MockCallWrapper.fail(mockCallUuid, holder.getMockCallName(), mockRequest, "Invoke Script error:" + e.getLocalizedMessage());
        }
    }

    /**
     * 返回 Wrapper
     *
     * @param ret 脚本执行返回结果
     * @param holder mock配置持有者
     * @param mockRequest mock 请求
     * @return 返回Wrapper
     */
    private MockCallWrapper buildWrapper(Object ret, AmcMockCallHolder holder, String mockRequest) {
        MockCallWrapper wrapper = new MockCallWrapper();
        wrapper.setSuccess(true);
        wrapper.setMockName(holder.getMockCallName());
        wrapper.setMockUuid(holder.getMockCallUuid());
        wrapper.setMockRequest(mockRequest);
        wrapper.setMockResponse(ret);
        return wrapper;
    }
}
